<?php

namespace App\Console\Commands;

use PHPExcel;
use PHPExcel_IOFactory;
use Illuminate\Console\Command;
use App\Http\Model\User;
use App\Http\Services\SystemServices;
use App\Lib\oss;


class CommandUserExcel extends Command
{
    protected $signature = 'CommandUserExcel';

    protected $description = '用户异步导出处理';

    protected $successLog = 'CommandUserExcel'; //日志
    protected $errorLog = 'error_CommandUserExcel'; //错误日志

    protected $ossLib;
    protected $userModel;
    protected $systemService;

    public function __construct()
    {
        parent::__construct();

        $this->ossLib = new oss();
        $this->userModel = new User();
        $this->systemService = new SystemServices();
    }

    public function handle()
    {
        set_time_limit(0);

        do {
            $list = $this->userModel->getUserExcelLogListByStatus(0);
            foreach($list as $val) {
                //锁
                $lockKey = 'USEREXCEL:HANDLE:'.$val['id'];
                if(!redis_lock($lockKey, 3600)){
                    continue;
                }

                //公会主播私信统计
                if($val['type'] == 1) {
                    $this->doUserExcelLog($val);
                }

                redis_unlock($lockKey);
            }

        } while (false);
    }

    //公会主播私信统计
    public function doUserExcelLog($log)
    {
        do {
            try {
                $condition = json_decode($log['condition'], true);
                $list = $this->userModel->getUnionUserMsgStatAll($condition['unionId'], $condition['timeSt'], $condition['timeEd']);

                //生成Excel
                $filePath = storage_path() . '/excel/公会主播私信统计-'.$log['id'].'.xlsx';
                $objPHPExcel = new PHPExcel();
                $objSheet = $objPHPExcel->getActiveSheet();
                $this->excelTemp($objSheet, $objPHPExcel, $list);
                $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
                $objWriter->save($filePath);

                //上传oss
                $url = $this->upLoadOss($filePath);
                if(empty($url)) {
                    write_log($this->errorLog, '公会主播私信统计 上传oss 失败', ['log'=>$log, 'filePath'=>$filePath]);
                    break;
                }
                //更新
                $this->userModel->updateUserExcelLog($log['id'], $url);

            } catch (\Exception $e) {
                write_log($this->errorLog, '公会主播私信统计 异常', ['log'=>$log, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);

            }
        } while (false);
    }

    //公会主播私信统计
    public function excelTemp($objSheet, $objPHPExcel, $dataList){
        //工作表标题
        $objSheet->setTitle("公会主播私信统计");
        // 设置活动的工作表索引到第一个工作表，所以 Excel 打开这是第一个工作表
        // $objPHPExcel->setActiveSheetIndex(0);
        //第一行内容，放列标题
        $objSheet->setCellValue("A1", "主播ID");
        $objSheet->setCellValue("B1", "主播昵称");
        $objSheet->setCellValue("C1", "私信总人数");
        $objSheet->setCellValue("D1", "私信总条数");
        $objSheet->setCellValue("E1", "新用户私信人数");
        $objSheet->setCellValue("F1", "新用户私信数");
        //设置第一行的背景颜色
        $objPHPExcel->getActiveSheet()
            ->getStyle('A1:M1')
            ->getFill()
            ->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)
            ->getStartColor()
            ->setRGB('FFFF00');
        //后面行循环放内容
        $lineNum = 2;
        foreach($dataList as $val) {
            $objSheet->setCellValue("A".$lineNum, $val['uuid']);
            $objSheet->setCellValue("B".$lineNum, $val['nickname']);
            $objSheet->setCellValue("C".$lineNum, $val['user_num']);
            $objSheet->setCellValue("D".$lineNum, $val['sms_num']);
            $objSheet->setCellValue("E".$lineNum, $val['new_use_num']);
            $objSheet->setCellValue("F".$lineNum, $val['new_sms_num']);
            $lineNum++;
        }
    }

    //上传OSS
    public function upLoadOss($localFilePath){
        //上传地址
        $upload_config = $this->systemService->get_put_file_url(24, 'xlsx');
        $formatUri = ltrim($upload_config[0]['uri'], '/');

        $ossRes = $this->ossLib->uploadFile($formatUri, $localFilePath);
        if (!$ossRes) {
           write_log($this->errorLog, '上传文件过程中发生错误',$ossRes);
           return '';
        }
        $url = '/'.$formatUri;
        return $url;
    }

}